# coding: utf-8
# code by https://cpp.la, 2020-04-20
# flask + gevent + multiprocess + wsgi

from gevent import monkey  # NOQA: E402
from gevent.pywsgi import WSGIServer  # NOQA: E402
monkey.patch_all()  # NOQA: E402

from multiprocessing import cpu_count, Process
from flask import Flask, request
from login import login
from process import get_data, get_data_card, get_data_eams


app = Flask(__name__)


@app.route('/', methods=['POST'])
def index():
    data = request.get_json()
    username = data['username']
    password = data['password']
    session = login(username, password)
    return get_data(session)


@app.route('/card', methods=['POST'])
def card():
    data = request.get_json()
    username = data['username']
    password = data['password']
    session = login(username, password)
    return get_data_card(session)


@app.route('/eams', methods=['POST'])
def eams():
    data = request.get_json()
    username = data['username']
    password = data['password']
    session = login(username, password)
    return get_data_eams(session)


def run(MULTI_PROCESS):
    if MULTI_PROCESS == False:
        WSGIServer(('0.0.0.0', 5000), app).serve_forever()
    else:
        mulserver = WSGIServer(('0.0.0.0', 5000), app)
        mulserver.start()

        def server_forever():
            mulserver.start_accepting()
            mulserver._stop_event.wait()

        for i in range(cpu_count()):
            p = Process(target=server_forever)
            p.start()


if __name__ == "__main__":
    # 单进程 + 协程
    run(False)
    # 多进程 + 协程
    # run(True)
